package org.lcc.Service.impl;

import org.lcc.Service.NotificationService;
import org.lcc.mapper.NotificationMapper;
import org.lcc.model.VO.NotificationVO;
import org.lcc.model.dto.NotificationDto;
import org.lcc.model.entity.Notification;
import org.lcc.model.entity.NotificationReceiver;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class NotificationServiceImpl implements NotificationService {

    @Autowired
    private NotificationMapper notificationMapper;

    @Override
    @Transactional
    public Map<String, Object> sendNotification(NotificationDto notificationDto, String senderId) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 创建通知
            Notification notification = new Notification();
            notification.setTitle(notificationDto.getTitle());
            notification.setContent(notificationDto.getContent());
            notification.setSenderId(senderId);
            notification.setNotificationType(notificationDto.getNotificationType());
            notification.setSendTime(LocalDateTime.now());
            notification.setStatus("active");
            notification.setPriority(notificationDto.getPriority() != null ? notificationDto.getPriority() : "normal");
            
            // 插入通知
            notificationMapper.insertNotification(notification);
            
            // 处理接收者
            if ("student".equals(notificationDto.getNotificationType())) {
                // 学生通知
                List<NotificationReceiver> receivers = new ArrayList<>();
                for (String studentId : notificationDto.getTargetIds()) {
                    NotificationReceiver receiver = new NotificationReceiver();
                    receiver.setNotificationId(notification.getNotificationId());
                    receiver.setTargetType("student");
                    receiver.setTargetId(studentId);
                    receiver.setReadStatus(false);
                    receivers.add(receiver);
                }
                if (!receivers.isEmpty()) {
                    notificationMapper.batchInsertReceivers(receivers);
                }
            } else if ("class".equals(notificationDto.getNotificationType())) {
                // 班级通知 - 修改为获取班级内所有学生并为每个学生创建通知接收记录
                List<NotificationReceiver> receivers = new ArrayList<>();
                
                for (String classId : notificationDto.getTargetIds()) {
                    // 获取班级中的所有学生
                    List<String> studentIds = notificationMapper.getClassStudents(classId);
                    
                    // 为每个学生创建通知接收记录
                    for (String studentId : studentIds) {
                        NotificationReceiver receiver = new NotificationReceiver();
                        receiver.setNotificationId(notification.getNotificationId());
                        receiver.setTargetType("student"); // 改为student类型
                        receiver.setTargetId(studentId);
                        receiver.setReadStatus(false);
                        receivers.add(receiver);
                    }
                    
                    // 同时保存班级通知记录（可选，用于记录这是发给哪个班级的）
                    NotificationReceiver classReceiver = new NotificationReceiver();
                    classReceiver.setNotificationId(notification.getNotificationId());
                    classReceiver.setTargetType("class");
                    classReceiver.setTargetId(classId);
                    classReceiver.setReadStatus(false);
                    receivers.add(classReceiver);
                }
                
                if (!receivers.isEmpty()) {
                    notificationMapper.batchInsertReceivers(receivers);
                }
            }
            
            result.put("success", true);
            result.put("message", "通知发送成功");
            result.put("notificationId", notification.getNotificationId());
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "通知发送失败: " + e.getMessage());
        }
        
        return result;
    }

    @Override
    public Map<String, Object> getAllNotifications(int pageNum, int pageSize) {
        Map<String, Object> result = new HashMap<>();
        
        // 计算偏移量
        int offset = (pageNum - 1) * pageSize;
        
        // 获取通知列表
        List<NotificationVO> notifications = notificationMapper.getAllNotifications(offset, pageSize);
        
        // 获取总数
        int total = notificationMapper.countAllNotifications();
        
        result.put("notifications", notifications);
        result.put("total", total);
        
        return result;
    }

    @Override
    public Map<String, Object> getStudentNotifications(String studentId, int pageNum, int pageSize) {
        Map<String, Object> result = new HashMap<>();
        
        // 计算偏移量
        int offset = (pageNum - 1) * pageSize;
        
        // 获取通知列表
        List<NotificationVO> notifications = notificationMapper.getStudentNotifications(studentId, offset, pageSize);
        
        // 获取总数
        int total = notificationMapper.countStudentNotifications(studentId);
        
        result.put("notifications", notifications);
        result.put("total", total);
        
        return result;
    }

    @Override
    public Map<String, Object> getTeacherNotifications(String teacherId, int pageNum, int pageSize) {
        Map<String, Object> result = new HashMap<>();
        
        // 计算偏移量
        int offset = (pageNum - 1) * pageSize;
        
        // 获取通知列表
        List<NotificationVO> notifications = notificationMapper.getTeacherNotifications(teacherId, offset, pageSize);
        
        // 获取总数
        int total = notificationMapper.countTeacherNotifications(teacherId);
        
        result.put("notifications", notifications);
        result.put("total", total);
        
        return result;
    }

    @Override
    public NotificationVO getNotificationDetail(Integer notificationId, String studentId) {
        NotificationVO notification = notificationMapper.getNotificationDetail(notificationId, studentId);
        return notification;
    }

    @Override
    @Transactional
    public boolean markAsRead(Integer notificationId, String studentId) {
        try {
            System.out.println(notificationId);
            System.out.println(studentId);
            int rows = notificationMapper.markAsRead(notificationId, studentId, LocalDateTime.now());
            System.out.println(rows);
            return rows > 0;
        } catch (Exception e) {
            return false;
        }
    }

    @Override
    public int countUnreadNotifications(String studentId) {
        return notificationMapper.countUnreadNotifications(studentId);
    }

    @Override
    public boolean deleteNotification(Integer notificationId) {
        try {
            int rows = notificationMapper.deleteNotification(notificationId);
            return rows > 0;
        } catch (Exception e) {
            return false;
        }
    }
} 